package tas.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tas.cbo.Combos;
import tas.dao.DaoHorarios;
import tas.dao.impl.DaoHorariosImpl;
import tas.xml.Xml;

@WebServlet(name = "ServletHorariosAsi", urlPatterns = {"/view/admin/HorariosAsi"})
public class ServletHorariosAsi extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String autorizacion = (String) request.getSession().getAttribute("autorizacion");
        String ID = (String) request.getSession().getAttribute("ID");

        if ((ID == null) || (autorizacion == null)
                || (!autorizacion.equals("ADMIN"))
                || (!ID.equals(request.getSession().getId()))) {

            response.sendRedirect("../");

        } else {

            request.setCharacterEncoding("UTF-8");
            String accion = request.getParameter("accion");
            String result = null;
            String target = null;
            String contentType = "text/html;charset=UTF-8";
            //
            DaoHorarios daoHorarios = new DaoHorariosImpl();

            if (accion == null) {
                result = "Solicitud no recibida";

            } else if (accion.equals("QRY")) {
                String filtro = null;
                String numdoc = request.getParameter("numdoc").trim();
                String appaterno = request.getParameter("appaterno").trim();
                String apmaterno = request.getParameter("apmaterno").trim();
                String nombres = request.getParameter("nombres").trim();
                String uejecutora = request.getParameter("uejecutora").trim();
                String annio = request.getParameter("annio").trim();
                String corte = request.getParameter("corte").trim();
                String sede = request.getParameter("sede").trim();
                String dependencia = request.getParameter("dependencia").trim();
                String area = request.getParameter("area").trim();
                String reglab = request.getParameter("reglab").trim();
                String estado = request.getParameter("estado");

                filtro = estado.equals("1") ? "  VIS_TRA.IDESTADOSIGA='1' " : "  VIS_TRA.IDESTADOSIGA='0'";

                filtro = filtro + " AND VIS_TRA.IDAÑO='" + annio + "' "
                        + "AND VIS_TRA.IDUNIDADEJECUTORA='" + uejecutora + "' "
                        + "AND VIS_TRA.IDCORTE='" + corte + "' ";

                if (numdoc.trim().length() > 0) {
                    filtro += " AND (VIS_TRA.NUMERODOCUMENTOIDENTIDAD='" + numdoc + "')";
                } else {
                    if (appaterno.length() > 0) {
                        filtro += " AND (upper(VIS_TRA.APELLIDOPATERNO) LIKE '%' || upper('" + appaterno + "') || '%') ";
                    }

                    if (apmaterno.length() > 0) {
                        filtro += " AND (upper(VIS_TRA.APELLIDOMATERNO) LIKE '%' || upper('" + apmaterno + "') || '%') ";
                    }

                    if (nombres.length() > 0) {
                        filtro += " AND (upper(VIS_TRA.NOMBRE) LIKE '%' || upper('" + nombres + "') || '%') ";
                    }
                    if (!reglab.equals("0")) {
                        filtro += " AND (VIS_TRA.IDREGIMENLABORAL=" + reglab + ")";
                    }

                    if (!dependencia.equals("0")) {
                        filtro += " AND (VIS_TRA.IDDEPENDENCIA =" + dependencia + ")";
                    }
                    if (!area.equals("0")) {
                        filtro += " AND (VIS_TRA.CODAREAINT  =" + area + ")";
                    }

                    if (!sede.equals("0")) {
                        filtro += " AND (VIS_TRA.IDSEDE  =" + sede + ")";
                    }
                }

                List<Object[]> list = daoHorarios.trabajadoresQry(filtro);

                if (list != null) {
                    if (list.isEmpty()) {
                        result = "Consulta no tiene resultados";
                    } else {
                        StringBuilder sb = new StringBuilder();

                        int cont = 1;

                        for (Object[] f : list) {
                            sb.append("<tr>");

                            sb.append("<th>").append("<input type=\"radio\" value=\"").append(f[0]).append("\" name=\"_upd\"/>").append("</th>");
                            sb.append("<td >").append(cont).append("</td>");
                            sb.append("<td id=\"_NomTra_").append(f[0]).append("\">").append(f[3]).append("</td>");
                            sb.append("<td>").append(f[4]).append("</td>");
                            sb.append("<td>").append(f[5]).append("</td>");
                            sb.append("<td>").append(f[6]).append("</td>");
                            sb.append("<td>").append(f[7]).append("</td>");

                            sb.append("<td>");
                            String horario = (f[8] == null) ? "" : f[8].toString();
                            String idhorariovigente = (f[9] == null) ? "" : f[9].toString();
                            sb.append(horario);
                            sb.append("<input type=\"hidden\" value=\"").append(idhorariovigente).append("\" id=\"_idh_").append(f[0]).append("\"/>").append("</th>");
                            sb.append("</td>");
                            sb.append("</tr>");
                            cont++;
                        }

                        result = "Ok!" + sb.toString();
                    }

                } else {
                    result = "Consulta no puede ser atendida";
                }

            } else if (accion.equals("GET_ASIG1")) {
                String id = request.getParameter("id");
                Integer idx = null;

                if (id != null) {
                    try {
                        idx = Integer.valueOf(id);
                    } catch (NumberFormatException e) {
                        result = "Valor errado de idtrabajador";
                    }
                } else {
                    result = "ID Trabajador no recibido";
                }

                if (result == null) {
                    String trabajador = daoHorarios.trabajadoresGet(idx);

                    Object[] ftit = {"trabajador_asi"};
                    Object[] fdat = {trabajador};

                    List<Object[]> list = new LinkedList<Object[]>();
                    list.add(ftit);
                    list.add(fdat);

                    Xml xml = new Xml();
                    StringBuilder data = xml.toXml(list);
                    result = data.toString();

                    contentType = "text/xml;charset=UTF-8";
                }

            } else if (accion.equals("GET_ASIG2")) {
                Combos cbo = new Combos();
                List<Object[]> list = cbo.horariosCbo();

                if ((list != null) && (list.size() > 0)) {
                    StringBuilder sb = new StringBuilder();

                    sb.append("<option value=\"0\">Seleccione...</option>");
                    for (Object[] f : list) {
                        sb.append("<option value=\"").append(f[0]).append("\">");
                        sb.append(f[1]);
                        sb.append("</option>");
                    }

                    result = sb.toString();
                } else {
                    result = "<option value=\"0\">Seleccione...</option>";
                }

            } else if (accion.equals("GET_ASIG3")) {
                String id = request.getParameter("id");
                Integer idx = null;

                if (id != null) {
                    try {
                        idx = Integer.valueOf(id);
                    } catch (NumberFormatException e) {
                        result = "Valor errado de idhorario";
                    }
                } else {
                    result = "ID horario no recibido";
                }

                if (result == null) {
                    List<Object[]> listh = daoHorarios.horariosGet(idx);

                    if (listh != null) {
                        int ctos = listh.size();

                        Object[] ftit = {
                            "turno_asi_lun", "turno_asi_mar", "turno_asi_mie",
                            "turno_asi_jue", "turno_asi_vie", "turno_asi_sab",
                            "turno_asi_dom"
                        };
                        Object[] fdat = {"", "", "", "", "", "", ""};

                        for (int i = 1; i < ctos; i++) {
                            fdat[i - 1] = listh.get(i)[1];
                        }

                        List<Object[]> list = new LinkedList<Object[]>();
                        list.add(ftit);
                        list.add(fdat);

                        Xml xml = new Xml();
                        StringBuilder data = xml.toXml(list);
                        result = data.toString();

                        contentType = "text/xml;charset=UTF-8";
                    } else {
                        result = "No se pudo obtener datos de horario";
                    }
                }

            } else if (accion.equals("ASI_HOR")) {
                String idtrabajador = request.getParameter("idtrabajador");
                String idhorario = request.getParameter("idhorario");

                try {
                    Integer idtrabajadorx = Integer.valueOf(idtrabajador);
                    Integer idhorariox = Integer.valueOf(idhorario);

                    result = daoHorarios.horarioParaTrabajador(idhorariox, idtrabajadorx);

                } catch (NumberFormatException e) {
                    result = "IDs recibidos deben ser enteros";
                }

            } else if (accion.equals("GET_CON")) {
                String id = request.getParameter("id");
                Integer idx = null;

                if (id != null) {
                    try {
                        idx = Integer.valueOf(id);
                    } catch (NumberFormatException e) {
                        result = "Valor errado de idhorario";
                    }
                } else {
                    result = "ID horario no recibido";
                }

                if (result == null) {
                    List<Object[]> listh = daoHorarios.horariosGet(idx);

                    if (listh != null) {
                        int ctos = listh.size();

                        Object[] ftit = {
                            "horario_con",
                            "turno_con_lun", "turno_con_mar", "turno_con_mie",
                            "turno_con_jue", "turno_con_vie", "turno_con_sab",
                            "turno_con_dom"
                        };

                        Object[] fdat = {
                            listh.get(0)[0], "", "", "", "", "", "", ""
                        };

                        for (int i = 1; i < ctos; i++) {
                            fdat[i] = listh.get(i)[1];
                        }

                        List<Object[]> list = new LinkedList<Object[]>();
                        list.add(ftit);
                        list.add(fdat);

                        Xml xml = new Xml();
                        StringBuilder data = xml.toXml(list);
                        result = data.toString();

                        contentType = "text/xml;charset=UTF-8";
                    } else {
                        result = "No se pudo obtener datos de horario";
                    }
                }

            } else {
                result = "Solicitud no reconocida";
            }

            if (result == null) {
                result = "";
            }

            if (target == null) {
                response.setContentType(contentType);
                PrintWriter out = response.getWriter();
                out.print(result);
                out.close();
            } else {
                RequestDispatcher dispatcher = request.getRequestDispatcher(target);
                dispatcher.forward(request, response);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
